﻿
function cutImg(imgsrc, width, height, container, bgColor) {
    var count = 0;
    var defaultImg = "/SysRes/images/no_img_manager.png";//加载错误默认显示的图片
    var img = document.createElement("img");
    img.src = imgsrc;
    var cvs = document.createElement("canvas");
    cvs.width = width;
    cvs.height = height;
    var context = cvs.getContext('2d');
    context.fillStyle = bgColor;
    context.rect(0, 0, width, height);
    context.fill();
    appendCvs(container);
    function appendCvs(container) {
        if (typeof container == "object") {
            container.html("").append(cvs);
        } else {
            var _container = document.querySelector(container);
            _container.innerHTML = "";
            _container.appendChild(cvs);
        }
    }
    var rate = width / height;
    img.onload = function () {
        var imgWidth = img.width, imgHeight = img.height;
        var rate = imgWidth / imgHeight;
        var dx, dy, sx, sy, cvsw = width, cvsh = height, cvsx = 0, cvsy = 0;
        if (imgWidth <= width && imgHeight <= height) {//宽高都小于canvas尺寸
            dx = imgWidth, dy = imgHeight;
            sx = 0, sy = 0;
            if (rate > 1) {
                cvsw = width, cvsh = cvsw / rate;
                cvsx = 0, cvsy = (height - cvsh) / 2;
            } else {
                cvsh = height, cvsw = cvsh * rate;
                cvsy = 0, cvsx = (width - cvsw) / 2;
            }
        } else if (rate < 1) {//宽度小于高度时
            dx = imgWidth, dy = dx;
            sx = 0, sy = (imgHeight - dy) / 2;
        } else {//高度小于宽度时
            dx = imgHeight, dy = dx;
            sx = (imgWidth - dx) / 2, sy = 0;
        }
        context.drawImage(img, sx, sy, dx, dy, cvsx, cvsy, cvsw, cvsh);
        //var dataImg=cvs.toDataURL("image/jpeg");
        appendCvs(container);
    }
    img.onerror = function () {
        count++;//防止图片一直加载不出来造成死循环
        (count < 2) && cutImg(defaultImg, width, height, container, bgColor);
    }
}


//右键插件初始化
function InitFileContextMenu() {
    //if ($("div.filelists").length > 0) {
    //    $("div.filelists").each(function (i, ele) {
    //        console.log(i);
    //        $(ele).contextmenu({
    //            target: '#multiple-upload-context-menu-' + $(ele).attr("field"),
    //            onItem: function (context, e) {
    //                //执行点击事件
    //                //ContextMenuItemClick(context, context.index(), $(e.currentTarget).attr("data-action"), $(ele).attr("field"));
    //                //console.log(context, context.index(), $(e.currentTarget).attr("data-action"));
    //            }
    //        });
    //    });
    //}

    if ($("div.filelists").length > 0) {
        $("div.filelists").each(function (i, ele) {
            //console.log(i);
            $(ele).contextmenu({
                target: '#file-context-menu',
                onItem: function (context, e) {
                    //执行点击事件
                    if ($(e.currentTarget).attr("id") == "copypath") { //复制
                        var copyTxt = context.attr("data-path");
                        $(e.currentTarget).attr("data-clipboard-text", copyTxt);
                    }
                    //console.log($(e.currentTarget).attr("id"), context.attr("data-path"));
                    //console.log(context, context.index(), $(e.currentTarget), context.attr("data-path"));
                },
            });
        });
        
    }

    //if ($(".filelists").length > 0) {
    //    $(".filelists").contextMenu('file-context-menu', {
    //        bindings: {
    //            'copypath': function (t) {
                    
    //            }
    //        }
    //    });
    //}
}


var CommonFun = {
    GetSelectList: function () {
        var res_list = new Array();
        var res = {};
        $(".filelists .select").each(function (i, e) {
            var temp = $(e).parent().data();
            res = {};
            res.AddTime = $.FormartDate("yyyy-MM-dd hh:mm:ss");
            res.CurPath = temp.path;
            res.EditTime = $.FormartDate("yyyy-MM-dd hh:mm:ss");
            res.FullPath = temp.path;
            res.Name = temp.filename;
            res.Size = 0;
            res.Suffix = temp.suffix;
            res.Type = temp.type;
            res_list.push(res);
        });
        return res_list;
    }
}

var FileOpera = {
    //是否有操作
    HasOpera: false, 
    //操作类型 , Copy or Cut or Move
    OperaType: "", 
    //操作文件门 {} 为空
    OperaCont: {} 
}

var ContextMenuFileManager = {
    Global: function () {
        //全局空白处的右键
    },
    Folder: function () {
        //文件夹上的右键
    },
    Image: function () {
        //图片上的右键
    },
    Zip: function () {
        //压缩包上的右键
    },
    Select: function () {
        //选中上的右键菜单
    }
}

var curFilePath = "";

var uploadPlugin;

$(function () {
    var Html_Build = "";

    function MakeHtml(item, ft) {
        //console.log(item,(item["CurPath"] + "/" + item["Name"]).replace(/\\/g, "/"));
        //先处理路径问题
        //解决win下面\问题  把\替换为/
        var src = (item["CurPath"] + "/" + item["Name"]).replace(/\\/g, "/");
        //文件路径
        var path = item["Type"] == "Directory" ? (item["CurPath"] + "/").replace(/\\/g, "/") : ((item["CurPath"] + "/" + item["Name"]).replace(/\\/g, "/"));

        //解决linux问题 
        src = ("/" + src).replace("//", "/");
        path = ("/" + path).replace("//", "/");


        var dir = item["CurPath"];
        if (dir.indexOf("/") != -1) {
            dir = "\\" + dir.replace("/", "\\") + "\\";
        } 


            Html_Build = "";
        Html_Build += "<div class=\"filelists\" data-path=\"" + path + "\" data-dir=\"" + dir + "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
        Html_Build += "    <div class=\"file-contain tooltips\" data-original-title=\"" + item["Name"] + "\" >";
        Html_Build += "        <div class=\"filecont\">";

        if (ft == "file-image-o") {
            Html_Build += "             <div class=\"" + ft + "\" data-imgurl=\"" + src + "\" ></div>";
        } else {
            //文件标识
            Html_Build += "             <i class=\"fa fa-" + ft + "\"></i>";
        }

        Html_Build += "        </div>";
        Html_Build += "        <div class=\"filetitle\" title=\"" + item["Name"] + "\"> " + item["Name"] + " </div>";
        Html_Build += "    </div>";
        Html_Build += "</div>";
        return Html_Build;
    }

    function MakeIcon(item) {
        var ft = "file-o";
        switch (item.Suffix.toLowerCase()) {
            case "":
                ft = "folder-o";
                break;
            case ".txt":
                ft = "file-text-o";
                break;
            case ".jpg":
            case ".png":
            case ".bmp":
            case ".jpeg":
            case ".gif":
                ft = "file-image-o";
                break;
            case ".psd":
                ft = "file-photo-o";
                break;
            case ".doc":
            case ".docx":
                ft = "file-word-o";
                break;
            case ".pdf":
                ft = "file-pdf-o";
                break;
            case ".xlsx":
            case ".xls":
                ft = "file-excel-o";
                break;
            case ".mp3":
                ft = "file-sound-o";
                break;
            case ".mp4":
            case ".flv":
                ft = "file-movie-o";
                break;
            case ".zip":
            case ".rar":
            case ".7z":
            case ".tar":
                ft = "file-zip-o";
                break;
            case ".ppt":
                ft = "file-powerpoint-o";
                break;
            case ".cs":
            case ".js":
            case ".css":
            case ".html":
            case ".aspx":
                ft = "file-code-o";
                break;
            case ".ttf":
            case ".woff":
            case ".woff2":
            case ".svg":
            case ".otf":
            case ".eot":
                ft = "font";
                break;
            default:
                ft = "file-o";
                break;
        }

        Html_Build = MakeHtml(item, ft);

        $(".tab-content").append(Html_Build);
    }

    //默认进来的时候加载
    function loadfilelist(dir) {
        //console.log(dir);
        dir = dir.replace(rootPath, ""); //替换掉根目录 , 首位符顺便也换掉
        dir = dir.replace(/\\/g, "/");
        //dir = dir.trimStart("/");
        //console.log(dir);
        loading("正在加载 , 请稍后");
        var url = appConfig.adminPath + "ashx/filemanage.ashx";
        var data = { dir: (arguments.length == 0 ? "/" : dir) };
        AjaxSubmit(url, "getlist", data, function (f, d) {
            $(".curpath").text(dir.replace(/\//g, "\\"));
            location.hash = dir;
            //console.log(f, d);
            loading_remove();
            if (f == 1) {
                if (d.result == -99) {
                    alert("登录超时 , 请重新登录", function () {
                        setTimeout(function () {
                            JumpLogin();
                        }, 500);
                    });
                } else {
                    uploadPlugin.folder = dir.trimStart('/');
                    $(".tab-content").html("");
                    $.each(d.returnval, function (i, e) {
                        MakeIcon(e);
                    });
                    $("div[data-imgurl]").each(function (i, e) {
                        var imgsrc = $(e).attr("data-imgurl");
                        cutImg(imgsrc, 158, 145, $(e), "#fff");
                        //五个参数，第一个是要截取的源图片，第二个是canvas宽，第三个是高，第四个是最终放图片的容器，注意这个容器会被清空，第五个是canvas背景颜色。
                    });
                    $(".tab-content").append("<div style=\"clear:both\"></div>");
                }
                InitFileContextMenu();
                curFilePath = dir + "/";
            }
            else {
                alert("加载失败,请刷新页面重试");
            }
        });
    }

    function InitFileManager() {
        if (location.hash == "") {
            loadfilelist("/");
        }
        else {
            loadfilelist(location.hash.trimStart('#'));
        }
    }



    function viewimg(src) {
        bootbox.dialog({
            message: "<div style='text-align:center;'><img src='" + src + "' style='max-width:100%;max-height:700px;'/></div>",
            title: "图片查看",
            buttons:
            {
                main:
                {
                    label: "关闭",
                    className: "blue",
                    callback: function () { }
                }
            }
        });
    }
    function viewmp4(src) {
        bootbox.dialog({
            message: "<div style='text-align:center;'><video src='" + src + "' controls='controls' style='max-width:100%;max-height:700px;'/></div>",
            title: "MP4预览",
            buttons:
            {
                main:
                {
                    label: "关闭",
                    className: "blue",
                    callback: function () { }
                }
            }
        });
    }

    //查看文件
    function viewfiles(data) {
        //console.log(data);
        switch (data.suffix.toLowerCase()) {
            case "":
                alert("未知文件");
                break;
            case ".txt":
                alert("不支持打开文本文件");
                break;
            case ".jpg":
            case ".png":
            case ".bmp":
            case ".jpeg":
            case ".gif":
                viewimg(data.path);
                break;
            case ".psd":
                alert("不支持打开PSD文件");
                break;
            case ".doc":
            case ".docx":
                alert("不支持打开Word文件");
                break;
            case ".pdf":
                alert("不支持打开PDF文件");
                break;
            case ".xlsx":
            case ".xls":
                alert("不支持打开Excel文件");
                break;
            case ".mp3":
                alert("不支持打开音频文件");
                break;
            case ".mp4":
                viewmp4(data.path);
                break;
            case ".flv":
                alert("不支持打开FLV文件");
                break;
            case ".zip":
            case ".rar":
            case ".7z":
            case ".tar":
                alert("不支持打开压缩包");
                break;
            case ".ppt":
                alert("不支持打开PPT文件");
                break;
            case ".cs":
            case ".js":
            case ".css":
            case ".html":
            case ".aspx":
                alert("不支持打开网站文件");
                break;
            case ".ttf":
            case ".woff":
            case ".woff2":
            case ".svg":
            case ".otf":
            case ".eot":
                alert("不支持打开字体文件");
                break;
            default:
                alert("未知文件");
                break;
        }
    }

    //双击的时候 如果是图片文件就打开
    $("body").delegate(".filelists", "dblclick ", function () {
        var _this = $(this);
        var dir = _this.attr("data-dir");
        var type = _this.attr("data-type");

        if (type == "Directory") {
            if (dir != "") {
                loadfilelist(dir);
            }
        }
        else {
            viewfiles(_this.data());
        }
    });
    //单击选中
    $("body").delegate(".filelists", "click", function () {
        var _this = $(this).find(".file-contain");
        var isSelect = _this.hasClass("select");
        if (isSelect) {
            _this.removeClass("select");
        }
        else {
            _this.addClass("select");
        }
    });


    //主页
    $(".action-home").on("click", function () {
        loadfilelist("/");
    });
    //返回
    $(".action-up").on("click", function () {
        var curpath = $(".curpath").text();
        if (curpath == "" || curpath == "\\") {
            return false;
        }
        else {
            curpath = curpath.substring(0, curpath.lastIndexOf('\\'));
            if (curpath == "") {
                loadfilelist("/");
            }
            else {
                loadfilelist(curpath);
            }
        }
    });
    //刷新
    $(".action-refresh").on("click", function () {
        var curpath = $(".curpath").text();
        loadfilelist(curpath);
    });
    //新建文件夹
    $(".action-newfolder").on("click", function () {
        bootbox.prompt("文件夹名称 (仅允许字母和数字)", function (res) {
            console.log(res);
            if (res == "" || res == null) {
                //如果是空或者null , 放弃创建
            }
            else {
                if (/^[A-Za-z0-9]+$/.test(res)) {
                    //可以进行下一步了
                    var curpath = $(".curpath").text().replace(/\\/g, "/");
                    loading("正在创建文件夹 , 请稍后");
                    var url = appConfig.adminPath + "ashx/filemanage.ashx";
                    var data = { dir: curpath, newdir: res };
                    AjaxSubmit(url, "createfolder", data, function (f, d) {
                        ///console.log(f, d);
                        loading_remove();
                        if (f == 1) {
                            if (d.result == -99) {
                                alert("登录超时 , 请重新登录", function () {
                                    setTimeout(function () {
                                        JumpLogin();
                                    }, 500);
                                });
                            } else {
                                //创建成功
                                loadfilelist($(".curpath").text());
                                //$(".tab-content").html("");
                                //$(".tab-content").append("<div style=\"clear:both\"></div>");
                            }
                        }
                        else {
                            alert("加载失败,请刷新页面重试");
                        }
                    });

                }
                else {
                    // 文件名不支持
                    alert("文件夹名称只允许为数字或者字母及其组合");
                    return false;
                }
            }

        });
    });

    //全选/取消全选
    $(".action-checkall").on("click", function () {
        var ischeck = $(this).attr("data-ischeck");
        if (ischeck == "false") {
            $(".filelists .file-contain").addClass("select");
            $(this).attr("data-ischeck", "true");
            $(this).find("span").text("取消");
        } else {
            $(".filelists .file-contain").removeClass("select");
            $(this).attr("data-ischeck", "false");
            $(this).find("span").text("全选");
        }
    });
    //常见问题
    $(".action-faq").on("click", function () {
        bootbox.dialog({
            message: $(".problems").html(),
            title: "常见问题",
            buttons:
            {
                main:
                {
                    label: "关闭",
                    className: "blue",
                    callback: function () { }
                }
            }
        });
    });

    //移动
    $(".action-cut").on("click", function () {
        FileOpera.HasOpera = true;
        FileOpera.OperaType = "Cut";
        FileOpera.OperaCont = CommonFun.GetSelectList();
        //如果没选择提示没选择 , 如果是当前目录则提示不能移动到当前目录
        if (FileOpera.OperaCont < 1) {
            notice("您没有选择任何文件", "warning");
            return false;
        }
        $(".action-paste").removeClass("hide");
    });
    //复制
    $(".action-copy").on("click", function () {
        FileOpera.HasOpera = true;
        FileOpera.OperaType = "Copy";
        FileOpera.OperaCont = CommonFun.GetSelectList();
        //如果没选择提示没选择
        if (FileOpera.OperaCont < 1) {
            notice("您没有选择任何文件", "warning");
            return false;
        }
        $(".action-paste").removeClass("hide");
    });
    //删除
    $(".action-remove").on("click", function () {
        FileOpera.HasOpera = true;
        FileOpera.OperaType = "Del";
        FileOpera.OperaCont = CommonFun.GetSelectList();
        //没有选择任何文件
        if (FileOpera.OperaCont < 1) {
            notice("您没有选择任何文件", "warning");
            return false;
        }
        var _this = $(this);
        //直接调用删除方法
        bootbox.confirm("<h4>确定要删除选中的文件吗?</h4><h4 class='font-red'><b>文件删除后无法恢复 , 请谨慎操作</b> </h4>", function (res) {
            if (res) {
                var data = { filelist: JSON.stringify(CommonFun.GetSelectList()) };
                Btn_Disabled(_this);
                AjaxSubmit(appConfig.adminPath + "ashx/filemanage.ashx", "delete", data, function (f, d) {
                    Btn_UnDisabled(_this);
                    if (f) {
                        //请求成功
                        if (parseInt(d.result) > 0) {
                            alert("删除成功 !", function () {
                                loadfilelist(location.hash.trimStart('#'));
                            });
                        }
                        else if (parseInt(d.result) == -99) {
                            alert("登录超时 , 请重新登录", function () {
                                setTimeout(function () {
                                    JumpLogin();
                                }, 500);
                            });
                        }
                        else if (parseInt(d.result) == -100) {
                            alert("权限不足 , 无法操作 !");
                        }
                        else {
                            alert("删除失败 , 请稍后重试 !");
                        }
                    }
                    else {
                        //请求失败
                        alert("请求出错 , 请稍后刷新重试 !");
                    }
                });
            }
        });
    });
    //粘贴
    $(".action-paste").on("click", function () {
        if (FileOpera.OperaCont < 1) {
            notice("您没有选择任何文件", "warning");
            return false;
        }
        //要把json里面cur路径的改过来
        var curPath = location.hash.trimStart("#") + "/";
        var _temp = FileOpera.OperaCont;
        _temp.forEach(function (i) {
            i.CurPath = curPath;
        });
        var _this = $(this);
        var data = { filelist: JSON.stringify(FileOpera.OperaCont) };
        Btn_Disabled(_this);
        AjaxSubmit(appConfig.adminPath + "ashx/filemanage.ashx", FileOpera.OperaType.toLowerCase(), data, function (f, d) {
            Btn_UnDisabled(_this);
            if (f) {
                //请求成功
                if (parseInt(d.result) > 0) {

                    FileOpera.HasOpera = false;
                    FileOpera.OperaType = "";
                    FileOpera.OperaCont = {};
                    $(".action-paste").addClass("hide");

                    alert("操作成功 !", function () {
                        loadfilelist(location.hash.trimStart('#'));
                    });
                }
                else if (parseInt(d.result) == -99) {
                    alert("登录超时 , 请重新登录", function () {
                        setTimeout(function () {
                            JumpLogin();
                        }, 500);
                    });
                }
                else if (parseInt(d.result) == -100) {
                    alert("权限不足 , 无法操作 !");
                }
                else {
                    alert("操作失败 , 请稍后重试 !");
                }
            }
            else {
                //请求失败
                alert("请求出错 , 请稍后刷新重试 !");
            }
        });

        $(".action-paste").addClass("hide");

    })


    function MakeUploadFileList(filelist) {
        var html = "";
        html += '<tr class="template-download fade in">';
        html += '    <td class="filename"><span>{{name}}</span></td>';
        html += '    <td class="filelength"><span>{{size}} KB</span></td>';
        html += '    <td>';
        html += '        <div class="progress progress-striped active">';
        html += '            <div class="progress-bar progress-bar-info" role="progressbar"  >';
        html += '            </div>';
        html += '        </div>';
        html += '    </td>';
        html += '</tr>';
        $("tbody.files").html("");
        $.each(filelist, function (i, e) {
            $("tbody.files").append(html.Render({ "name": e.name, "size": parseFloat(e.size / 1024).toFixed(2) }));
        });

    }



    //文件上传
    uploadPlugin = $("#addFiles").Uploads({
        stopbtn: $(".filemanager-upload-cancel"),
        url: appConfig.adminPath + "ashx/upload.ashx",
        folder: curFilePath,
        safecode: parseInt(Math.random() * 100),
        onselect: function (fileLists) {
            MakeUploadFileList(fileLists);
        },
        process: function (process, i, fileList, field) {
            //console.log(process, i, fileList, field);
            if (process === 100) {
                $("tbody.files .progress-bar").eq(i - 1).css("width", process + "%").removeClass("progress-bar-info").addClass("progress-bar-success").parent().removeClass("active");
            }
            else {
                $("tbody.files .progress-bar").eq(i - 1).css("width", process + "%");
            }
        },
        success: function (flag, succList, i, field) {
            if (flag) {
                $(".action-refresh").click();
                alert(succList.length + "个文件上传成功");
            }
        },
        before: function (fileList, field) {
        },
        complate: function (field) {
        },
        error: function (xhr_respons, i, field) {
            //console.log(xhr_respons, i, field);
            $("tbody.files .progress-bar").eq(i).closest("td").html("<span class='font-red'>" + xhr_respons.trimStart("ERROR=") + "</span>");
        }
    });

    InitFileManager();

});  

